# $Id: FilterFormStats.pm,v 1.1 2004/02/29 19:18:42 ibo Exp $

package CGI::FOGE2::FilterFormStats;
use strict;
use CGI::FOGE2::Form;
use CGI::FOGE2::Tools;

our @ISA = ();

sub new {
    my $proto = shift;
    my $class = ref($proto) || $proto;
    my $params = [ @_ ];

    my $self = {
        form => undef,
    };

    bless $self, $class;
    return $self;
}

sub setform {
    my $self = shift;
    my ($form) = @_;
    $self->{form} = $form;
}

# Just report the number of total answers in HTML.

sub getstats {
    my $self = shift;
    my $form = $self->{form};

    my $out = '';
    $out .= CGI::p({ -class => 'formhead'}, "FILTERRRRRRRRRRrrRRRrrRrrrRrRrRrRrRrRrRr");
    $out .= CGI::table({ -align => 'center'}, $self->get_all_answers());
    return $out;
}

sub get_all_answers {
    my $self = shift;
    my $form = $self->{form};
    my $db = $form->dbh_r();
    my $filter = $form->{filter}->{name};
    my $tab_and_cols = $self->get_tables();

    my $request = "select * from $filter;";
    print STDERR $request, "\n";

    #my $out = CGI::Tr ({ -class => 'statrow'}, CGI::th({ -class => 'statrow'}, ['', 'id', @columns]));

    my $sth = $db->prepare($request);
    $sth->execute();
    my $out = '';
    while (my $row = $sth->fetchrow_arrayref()) {
	print STDERR join " | ", @$row, "\n";
	$out .= CGI::Tr( { -class => 'statrow'},
			 CGI::td([CGI::checkbox( -name => 'show_id',
						 -checked => 1,
						 -value => $$row[0],
						 -label => ''),
				  @$row]));
    }
    $sth->finish();

    return $out;    
}
 

# A hash where the keys are the table names and the
# values are arrays of the columns in those tables
sub get_tables {
    my $self = shift;
    my $form = $self->{form};
    my %tables = ();
    
    for my $section (@{$form->{sections}}) {
	my $table = $section->get_table_name();
	print STDERR "UNE TABLE:   $table .\n"; 
	next unless defined CGI::param($table);
	for my $question (@{$section->{questions}}) {
	    print STDERR "UNE QUESTION:  ${$question->generate_field_names()}[0].\n"; 
	    next unless defined CGI::param(${$question->generate_field_names()}[0]);
	    push @{$tables{$table}}, ${$question->generate_field_names()}[0];
	}
    }

    return \%tables;
}
1;

# end of FormStats.pm
